
/*
 基文件
 */

#define KEYWINDOW [UIApplication sharedApplication].delegate.window

#import "HBaseViewController.h"
#import <CommonCrypto/CommonHMAC.h>
#import<CommonCrypto/CommonCryptor.h>
#import <AFNetworking.h>
//#import "RegisterAndLoginViewController.h"
@interface HBaseViewController ()

@end

@implementation HBaseViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = RGB(79, 113, 161);
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor whiteColor]};
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//#pragma mark 弹窗 alert  confirm

-(void) alert:(NSString*)msg {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        //callback();
    }]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    });
}

// 阴影
- (UIButton *)coverBtn {
    if (!_coverBtn) {
        _coverBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
        _coverBtn.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        _coverBtn.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.3];
        [_coverBtn addTarget:self action:@selector(clickedCoverBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _coverBtn;
}

- (void)clickedCoverBtnAction:(UIButton*)sender {
    UIView *superView = sender.superview;
    UIView *outsideView = [superView.subviews lastObject];
    [UIView animateWithDuration:1 animations:^{
        [outsideView removeFromSuperview];
        [KEYWINDOW addSubview:_coverBtn];
    } completion:^(BOOL finished) {
        [_coverBtn removeFromSuperview];
        _coverBtn = nil;
    }];
}

- (void)ManagerGET:(NSString *)URLString
        parameters:(id)parameters
            header:(NSString *)header
           success:(void (^)(id))success
           failure:(void (^)(NSError *))failure {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    [manager.securityPolicy setAllowInvalidCertificates:YES];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:F(@"Token %@", header) forHTTPHeaderField:@"Authorization"];
    [manager GET:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (operation.response.statusCode == 200) {
            success(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"cuowu:%@,%ld",error,operation.response.statusCode);
        if (operation.response.statusCode == 400) {
            
        }
    }];
}

- (void)ManagerPost:(NSString *)URLString
         parameters:(id)parameters
             header:(NSString *)header
            success:(void (^)(id))success
            failure:(void (^)(NSError *))failure {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    [manager.securityPolicy setAllowInvalidCertificates:YES];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:F(@"Token %@", header) forHTTPHeaderField:@"Authorization"];
    [manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (operation.response.statusCode == 200) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        if (operation.response.statusCode == 400) {
            
        }
    }];
}
- (void)receivePOSTWithTokenURLString:(NSString *)string
                               method:(NSString *)method
                                 body:(NSString *)body
                                Token:(NSString *)Token
                               Blocks:(Blocks)blocks {
    
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:method];
    [request setTimeoutInterval:30];
    if ([method isEqualToString:@"POST"] || [method isEqualToString:@"PATCH"]) {
        NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        if (Token)
        {
            [request setValue: Token forHTTPHeaderField:@"Authorization"];
            [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
            [request setValue:@"ios" forHTTPHeaderField:@"platform"];
            
        }
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        request = [request copy];
    }
    if ([method isEqualToString:@"GET"]) {
        if (body) {
            NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
            [request setHTTPBody:data];
        }
        [request setValue:Token forHTTPHeaderField:@"Authorization"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
        request = [request copy];
    }
    NSHTTPURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];
    NSString *result =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"result:%@ %ld",result,(long)response.statusCode);
    if (data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
        NSString *firstCode = [F(@"%ld", (long)response.statusCode) substringToIndex:1];
        if ([firstCode isEqualToString:@"2"]) {
            if (data != nil) {
                blocks(dic,response.statusCode);
            }
        }else if (response.statusCode == 400) {
            [HCommon dismissMessage];
            if (dic && [dic valueForKey:@"error_msg"] && [[dic allKeys] containsObject:@"error_msg"]) {
                [self alert:F(@"%@",[dic valueForKey:@"error_msg"]?:@"网络错误")];
            }else {
                NSArray *keyArray = [dic allKeys];
                NSMutableArray *errorDetailArray = [NSMutableArray new];
                for (int i = 0; i < keyArray.count; i ++) {
                    [errorDetailArray addObject:[dic valueForKey:keyArray[i]][0]];
                }
                [self alert:[errorDetailArray componentsJoinedByString:@";"]];
            }
        }else if (response.statusCode == 401) {
            //            RegisterAndLoginViewController *VC = [[RegisterAndLoginViewController alloc]init];
            //            [self.navigationController pushViewController:VC animated:YES];
        }else if (response.statusCode == 403) {
            [self alert:F(@"%@",[dic valueForKey:@"error_msg"]?:@"您没有权限执行此操作")];
        }else if (response.statusCode == 404) {
            if ([dic valueForKey:@"error_msg"]) {
                blocks(nil,response.statusCode);
            }else {
                [self alert:@"网络错误,请重试!"];
            }
        }else if (response.statusCode == 500) {
            [HCommon dismissMessage];
            [self alert:F(@"%@",[dic valueForKey:@"error_msg"]?:@"网络错误请重试")];
        }else {
            [self alert:@"网络错误,请重试!"];
        }
    }
}
- (NSString *)dictionaryToJson:(NSDictionary *)dic {
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (NSString *)urlUTF8:(NSString *)url {
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    return url;
}

- (UIImage *)fixOrientation:(UIImage *)aImage {
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (BOOL)isPureInt:(NSString*)string {
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}
//获取前后时间
-(NSString *)getNDay:(NSInteger)n{
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    if(n!=0) {
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        theDate = [nowDate initWithTimeIntervalSinceNow: oneDay*n ];//initWithTimeIntervalSinceNow是从现在往前后推的秒数
    }else{
        theDate = nowDate;
    }
    NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
    [date_formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *the_date_str = [date_formatter stringFromDate:theDate];
    return the_date_str;
}

-(NSMutableArray *)latelySevenTime{
    NSMutableArray *SevenArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < 7; i ++) {
        NSTimeInterval secondsPerDay = (i + 1 - 7)* 24*60*60;
        NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *dateStr = [dateFormatter stringFromDate:curDate];
        NSString *strTime = [NSString stringWithFormat:@"%@",dateStr];
        [SevenArr addObject:strTime];
    }
    return SevenArr;
}
@end
